package org.example.concurrent.reference;

import java.lang.ref.SoftReference;

public class SoftReferenceDemo {

    /**
     * 内存够用就保留，不够就回收
     */
    public static void softRef_Memory_Enough() {
        Object o1 = new Object();
        SoftReference<Object> softReference = new SoftReference<>(o1);
        System.out.println(o1); //java.lang.Object@14ae5a5
        System.out.println(softReference.get()); //java.lang.Object@14ae5a5

        o1 = null;
        System.gc();

        System.out.println(o1); //null
        System.out.println(softReference.get()); //java.lang.Object@14ae5a5
    }

    /**
     * 生成大对象，设置小内存，自动GC
     * -Xms5m -Xmx5m -XX:+PrintGCDetails
     */
    public static void softRef_Memory_NotEnough() {
        Object o1 = new Object();
        SoftReference<Object> softReference = new SoftReference<>(o1);
        System.out.println(o1);
        System.out.println(softReference.get());

        o1 = null;

        try {
            // 创建大对象
            byte[] bytes = new byte[30 * 1024 * 1024];
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            System.out.println(o1); //null
            System.out.println(softReference.get()); //null
        }
    }

    public static void main(String[] args) {
        softRef_Memory_Enough();
        softRef_Memory_NotEnough();
    }
}

